package com.nettywork.communication;

import com.nettywork.base.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class ChatClient {

    public static void main(String args[]) {
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline cp = socketChannel.pipeline();
                            //可以添加很多handler  比如 String 编码解码handler 还有自定义的handler
                            cp.addLast(new DelimiterBasedFrameDecoder(2048, Unpooled.copiedBuffer("^".getBytes())));
                            cp.addLast("decoder", new StringDecoder());
                            cp.addLast("encoder", new StringEncoder());
                            cp.addLast(new ChatClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6999).sync();
            Channel channel = channelFuture.channel();
//            while (true) {
//                Scanner scanner = new Scanner(System.in);
//                String msg = scanner.next();
//                if(msg.equals("exit")){
//                    //channel.close();
//                    channelFuture.addListener(ChannelFutureListener.CLOSE);
//                    break;
//                }
//                channel.write(msg);
//                channel.flush();
//            }
            for(int i=0; i<100; i++){
                channel.writeAndFlush("hello netty"+"^");
            }
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workGroup.shutdownGracefully();
        }
    }
}


